import { Request, Response } from 'express';
import { getRepository } from 'typeorm';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { User } from '../models/User';
import { AuthRequest } from '../middlewares/auth';

export const register = async (req: Request, res: Response) => {
  try {
    const { username, password, email, phone, role } = req.body;

    const userRepository = getRepository(User);
    const existingUser = await userRepository.findOne({ where: { username } });

    if (existingUser) {
      return res.status(400).json({ message: '用户名已存在' });
    }

    const hashedPassword = await bcrypt.hash(password, 10);
    const user = userRepository.create({
      username,
      password: hashedPassword,
      email,
      phone,
      role: role || 'user'
    });

    await userRepository.save(user);

    const token = jwt.sign(
      { id: user.id },
      process.env.JWT_SECRET || 'your_jwt_secret_key',
      { expiresIn: process.env.JWT_EXPIRES_IN || '24h' }
    );

    res.status(201).json({
      message: '注册成功',
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        role: user.role
      }
    });
  } catch (error) {
    res.status(500).json({ message: '注册失败', error: error.message });
  }
};

export const login = async (req: Request, res: Response) => {
  try {
    const { username, password } = req.body;

    const userRepository = getRepository(User);
    const user = await userRepository.findOne({ where: { username } });

    if (!user) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    const isValidPassword = await bcrypt.compare(password, user.password);
    if (!isValidPassword) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    const token = jwt.sign(
      { id: user.id },
      process.env.JWT_SECRET || 'your_jwt_secret_key',
      { expiresIn: process.env.JWT_EXPIRES_IN || '24h' }
    );

    res.json({
      message: '登录成功',
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        role: user.role
      }
    });
  } catch (error) {
    res.status(500).json({ message: '登录失败', error: error.message });
  }
};

export const getProfile = async (req: AuthRequest, res: Response) => {
  try {
    if (!req.user) {
      return res.status(401).json({ message: '请先登录' });
    }

    res.json({
      user: {
        id: req.user.id,
        username: req.user.username,
        email: req.user.email,
        role: req.user.role
      }
    });
  } catch (error) {
    res.status(500).json({ message: '获取用户信息失败', error: error.message });
  }
};

export const updateProfile = async (req: AuthRequest, res: Response) => {
  try {
    if (!req.user) {
      return res.status(401).json({ message: '请先登录' });
    }

    const { email, phone } = req.body;
    const userRepository = getRepository(User);

    await userRepository.update(req.user.id, { email, phone });
    const updatedUser = await userRepository.findOne({ where: { id: req.user.id } });

    res.json({
      message: '更新成功',
      user: {
        id: updatedUser?.id,
        username: updatedUser?.username,
        email: updatedUser?.email,
        role: updatedUser?.role
      }
    });
  } catch (error) {
    res.status(500).json({ message: '更新失败', error: error.message });
  }
};

// 获取用户列表
export const getUsers = async (req: Request, res: Response) => {
  try {
    const { page = 1, pageSize = 10, username, role } = req.query;
    const userRepository = getRepository(User);
    
    const queryBuilder = userRepository.createQueryBuilder('user');
    
    if (username) {
      queryBuilder.andWhere('user.username LIKE :username', { username: `%${username}%` });
    }
    
    if (role) {
      queryBuilder.andWhere('user.role = :role', { role });
    }
    
    const [users, total] = await queryBuilder
      .skip((Number(page) - 1) * Number(pageSize))
      .take(Number(pageSize))
      .getManyAndCount();
    
    res.json({
      data: users.map(user => ({
        id: user.id,
        username: user.username,
        email: user.email,
        role: user.role,
        status: user.status,
        createdAt: user.createdAt
      })),
      total,
      page: Number(page),
      pageSize: Number(pageSize)
    });
  } catch (error: any) {
    res.status(500).json({ message: '获取用户列表失败', error: error.message });
  }
};

// 创建用户
export const createUser = async (req: Request, res: Response) => {
  try {
    const { username, password, email, role, status } = req.body;
    const userRepository = getRepository(User);
    
    const existingUser = await userRepository.findOne({ where: { username } });
    if (existingUser) {
      return res.status(400).json({ message: '用户名已存在' });
    }
    
    const hashedPassword = await bcrypt.hash(password, 10);
    const user = userRepository.create({
      username,
      password: hashedPassword,
      email,
      role,
      status: status || 'active'
    });
    
    await userRepository.save(user);
    
    res.status(201).json({
      message: '创建用户成功',
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        role: user.role,
        status: user.status,
        createdAt: user.createdAt
      }
    });
  } catch (error: any) {
    res.status(500).json({ message: '创建用户失败', error: error.message });
  }
};

// 更新用户
export const updateUser = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { email, role, status } = req.body;
    const userRepository = getRepository(User);
    
    const user = await userRepository.findOne({ where: { id: Number(id) } });
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    await userRepository.update(id, { email, role, status });
    const updatedUser = await userRepository.findOne({ where: { id: Number(id) } });
    
    res.json({
      message: '更新用户成功',
      user: {
        id: updatedUser?.id,
        username: updatedUser?.username,
        email: updatedUser?.email,
        role: updatedUser?.role,
        status: updatedUser?.status,
        createdAt: updatedUser?.createdAt
      }
    });
  } catch (error: any) {
    res.status(500).json({ message: '更新用户失败', error: error.message });
  }
};

// 删除用户
export const deleteUser = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const userRepository = getRepository(User);
    
    const user = await userRepository.findOne({ where: { id: Number(id) } });
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    await userRepository.remove(user);
    
    res.json({ message: '删除用户成功' });
  } catch (error: any) {
    res.status(500).json({ message: '删除用户失败', error: error.message });
  }
}; 